package ui

import (
	"log"
	"uselesscapslock/config"
	"uselesscapslock/platform"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
)

var configWindow fyne.Window

// 存储映射行的结构
type mappingRow struct {
	container *fyne.Container
	sourceKey *widget.Select
	targetKey *widget.Select
	deleteBtn *widget.Button
}

func ShowConfigWindow(app fyne.App) {
	// 如果窗口已存在，则显示现有窗口
	if configWindow != nil {
		configWindow.Show()
		return
	}

	// 创建新窗口
	configWindow = app.NewWindow("按键映射配置")

	// 加载现有配置
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Printf("加载配置失败: %v\n", err)
		cfg = &config.Config{}
	}

	// 创建映射列表容器
	mappingsContainer := container.NewVBox()
	var mappingRows []mappingRow

	// 添加映射的函数
	addMapping := func() mappingRow {
		sourceSelect := widget.NewSelect([]string{
			"CapsLock",
			"LCtrl", "RCtrl",
			"LAlt", "RAlt",
			"LShift", "RShift",
			"LWin", "RWin",
			"Tab", "Esc", "Space", "Enter", "Backspace",
			"Insert", "Delete", "Home", "End", "PgUp", "PgDn",
			"F1", "F2", "F3", "F4", "F5", "F6",
			"F7", "F8", "F9", "F10", "F11", "F12",
		}, nil)

		destSelect := widget.NewSelect([]string{
			"CapsLock",
			"LCtrl", "RCtrl",
			"LAlt", "RAlt",
			"LShift", "RShift",
			"LWin", "RWin",
			"Tab", "Esc", "Space", "Enter", "Backspace",
			"Insert", "Delete", "Home", "End", "PgUp", "PgDn",
			"F1", "F2", "F3", "F4", "F5", "F6",
			"F7", "F8", "F9", "F10", "F11", "F12",
		}, nil)

		deleteBtn := widget.NewButton("删除", nil)

		row := container.NewHBox(
			sourceSelect,
			widget.NewLabel("→"),
			destSelect,
			deleteBtn,
		)

		mappingRow := mappingRow{
			container: row,
			sourceKey: sourceSelect,
			targetKey: destSelect,
			deleteBtn: deleteBtn,
		}

		// 设置删除按钮的动作
		deleteBtn.OnTapped = func() {
			// 从容器中移除行
			mappingsContainer.Remove(row)
			// 从映射行列表中移除
			for i, r := range mappingRows {
				if r.container == row {
					mappingRows = append(mappingRows[:i], mappingRows[i+1:]...)
					break
				}
			}
		}

		mappingsContainer.Add(row)
		return mappingRow
	}

	// 添加现有映射
	for _, mapping := range cfg.Mappings {
		row := addMapping()
		row.sourceKey.SetSelected(mapping.SourceKey)
		row.targetKey.SetSelected(mapping.DestinationKey)
		mappingRows = append(mappingRows, row)
	}

	// 添加新映射按钮
	addButton := widget.NewButton("添加映射", func() {
		row := addMapping()
		mappingRows = append(mappingRows, row)
	})

	// 保存按钮
	saveButton := widget.NewButton("保存", func() {
		var newMappings []config.KeyMapping
		for _, row := range mappingRows {
			if row.sourceKey.Selected != "" && row.targetKey.Selected != "" {
				newMappings = append(newMappings, config.KeyMapping{
					SourceKey:      row.sourceKey.Selected,
					DestinationKey: row.targetKey.Selected,
				})
			}
		}

		newConfig := &config.Config{
			Mappings: newMappings,
		}

		if err := config.SaveConfig(newConfig); err != nil {
			log.Printf("保存配置失败: %v\n", err)
			return
		}

		// 重新加载键盘管理器配置
		if err := platform.GetKeyboardManager().ReloadConfig(); err != nil {
			log.Printf("重新加载配置失败: %v\n", err)
			return
		}

		log.Println("配置已保存并重新加载")
	})

	// 创建主容器
	mainContainer := container.NewVBox(
		mappingsContainer,
		container.NewHBox(
			addButton,
			saveButton,
		),
	)

	configWindow.SetContent(mainContainer)
	configWindow.Resize(fyne.NewSize(400, 300))

	// 设置窗口关闭时的行为
	configWindow.SetCloseIntercept(func() {
		configWindow.Hide() // 隐藏窗口而不是关闭
	})

	configWindow.Show()
}
